package com.loginlib.login.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.loginlib.R;
import com.loginlib.di.component.DaggerLoginActivityComponent;
import com.loginlib.di.component.LoginActivityComponent;
import com.loginlib.di.module.LoginModule;
import com.loginlib.panel.ILoginView;
import com.loginlib.presenters.UserCenterPresenter;
import com.wanhe.base.util.RegularUtil;
import com.wanhe.base.util.SPUtils;
import com.wanhe.base.util.ViewUtil;
import com.wanhe.qrcode.CaptureActivity;

import javax.inject.Inject;


/**
 * 服务器设置    自定义对话框
 *
 * @author niwenchi
 */
public class SetDialog extends Dialog implements OnClickListener,ILoginView {

    private Context context;
    private Button btnConfrim, btnCancle, btnClear;
    private EditText etIp, etPort;
    private RegularUtil regularUtil;//正则表达式工具
    private CheckBox repratOrder;
    private TextView tvVison;
    private CheckBox demonstration;
    private EditText waiterAccount;
    private EditText waiterPsw;
    @Inject
    UserCenterPresenter presenter;
    LoginActivityComponent loginActivityComponent;

    public SetDialog(Context context) {
        super(context, R.style.basedialog);
        this.context = context;
        regularUtil = new RegularUtil();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //设置Dialog没有标题，这个一定要在设置内容之前定义,不然会报错
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.dialogset);
        setCancelable(false);//加这个方法后，点击dialog视图以外的区域，dialog不会关闭，设置为true就会关闭
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        initInject();
        btnCancle = (Button) findViewById(R.id.btnCancle);
        btnConfrim = (Button) findViewById(R.id.btnConfrim);
        btnClear = (Button) findViewById(R.id.btnClear);
        tvVison = (TextView) findViewById(R.id.tvVison);
        repratOrder = (CheckBox) findViewById(R.id.cb_repeat_order);
        demonstration = (CheckBox) findViewById(R.id.cb_demonstration_btn);


        boolean isDom = SPUtils.getIsDemoSchema();
        demonstration.setChecked(isDom);

        demonstration.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    SPUtils.setIsSchema(true);
                } else {
                    SPUtils.setIsSchema(false);
                }
            }
        });

        btnCancle.setOnClickListener(this);
        btnConfrim.setOnClickListener(this);
        btnClear.setOnClickListener(this);

        try {
            tvVison.setText("V" + context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        etIp = (EditText) findViewById(R.id.etIp);
        etPort = (EditText) findViewById(R.id.etPort);

        if (!TextUtils.isEmpty(SPUtils.getIp()) && !TextUtils.isEmpty(SPUtils.getPort())) {
            etIp.setText(SPUtils.getIp());
            etPort.setText(SPUtils.getPort());
        }

        if (SPUtils.getValidatePwd()) {
            repratOrder.setChecked(true);
        } else {
            repratOrder.setChecked(false);
        }

        waiterAccount = (EditText) findViewById(R.id.et_account_input);
        waiterPsw = (EditText) findViewById(R.id.et_password_input);
        presenter.setLoadingView(this);
    }
//
    public void initInject(){
        loginActivityComponent =  DaggerLoginActivityComponent.builder().loginModule(new LoginModule(getContext())).build();
        loginActivityComponent.inject(this);
    }
    @Override
    public void onClick(View v) {

        int i = v.getId();
        if (i == R.id.btnConfrim) {
            String strIp = etIp.getText().toString();
            String strPort = etPort.getText().toString();
            String waiterAccountStr = waiterAccount.getText().toString();
            String waiterPswStr = waiterPsw.getText().toString();


            if (TextUtils.isEmpty(strIp)
                    || TextUtils.isEmpty(strPort)
                    || TextUtils.isEmpty(waiterAccountStr)
                    || TextUtils.isEmpty(waiterPswStr)) {
                Toast.makeText(context, "请将信息填写完整！", Toast.LENGTH_SHORT).show();
                return;
            }

            // 判断ip格式
            if (!regularUtil.ipCheck(strIp)) {
                Toast.makeText(context, "IP地址格式不正确！", Toast.LENGTH_SHORT).show();
                return;
            }

            if (!regularUtil.portCheck(strPort)) {
                Toast.makeText(context, "端口格式不正确！", Toast.LENGTH_SHORT).show();
                return;
            }

            /**
             * 根据issue 105中提及的需求，对这部分的代码进行改造
             * 改造需求为如果设置IP地址，需要对输入的服务员账号和密码进行验证
             * 如果验证不能通过，设置无效
             *
             * @author 陈德基
             * create at 2017/6/5 10:00
             */

            //访问网络，传入IP地址和端口号，以及用户名和密码验证

            presenter.checkLogin(strIp, strPort,waiterAccountStr, waiterPswStr);
//                            SharePUtil.getInstance().setAppIp(strIp);
//                            SharePUtil.getInstance().saveAppPort(strPort);
//                            SharePUtil.getInstance().setCheck(repratOrder.isChecked());
//                            dismiss();// 将当前对话框关闭

        } else if (i == R.id.btnCancle) {
            dismiss();//将当前对话框关闭

        } else if (i == R.id.btnClear) {
            CaptureActivity.startCaptureActivity((Activity)context);
        }
    }




    @Override
    public void onLoading() {
        ViewUtil.loadingDialog((Activity) context);
    }

    @Override
    public void onLoaded() {
        ViewUtil.dismissLoadingDialog();
    }

    @Override
    public void onLoadFail(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        ViewUtil.dismissLoadingDialog();
    }

    @Override
    public void loginSuccess(String account, String password) {

    }

    @Override
    public void checkLoginSuccess(String ip, String port) {
        SPUtils.setIp(ip);
        SPUtils.setPort( port);
        SPUtils.setValidatePwd(repratOrder.isChecked());
        ViewUtil.dismissLoadingDialog();
//        presenter.onDestory();
        Toast.makeText(context, "应用初始化设置成功", Toast.LENGTH_SHORT).show();
        dismiss();// 将当前对话框关闭
    }

    @Override
    public void updateVersion(String url) {

    }
}
